package com.ebc.eservice.service.impl.login;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ebc.eservice.mapper.RoleMapper;
import com.ebc.eservice.mapper.UserMapper;
import com.ebc.eservice.pojo.EbcRole;
import com.ebc.eservice.pojo.EbcUser;
import com.ebc.eservice.pojo.UserDT;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @author: Joey
 * @Description: 自定义 spring-security登录验证
 * @date:2022/9/19 0:55
 */
@Service
public class UserSecurityService implements UserDetailsService {

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {


//        QueryWrapper<EbcUser> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("account", username);
        EbcUser user = userMapper.selectOne(Wrappers.<EbcUser>lambdaQuery()
                .and(   wrapper -> wrapper
                        .eq(EbcUser::getAccount, username)
                        .or()
                        .eq(EbcUser::getPhone, username))
                        .eq(EbcUser::getOpen,1)
                .last("limit 1"));
        if(ObjectUtils.isEmpty(user)){
            return null;
        }
        //加密处理
        String encode = new BCryptPasswordEncoder().encode(user.getPassword());
        user.setPassword(encode);
        List<EbcRole> roles = roleMapper.getUserRolesByUid(user.getId());

        return new UserDT(user,roles);
    }
}

